<?php

namespace App\Controller\Index;

use Common\Model\MemberCollectionModel;
use Common\Model\MemberModel;
use Common\Model\MemberProfitModel;
use Common\Model\NeighbourhoodsModel;
use Common\Model\AdminModel;
use Common\Model\BannerModel;
use Common\Model\CheckModel;
use Common\Model\ConfigureModel;
use Common\Model\HousekeeperCommentModel;
use Common\Model\HousingModel;
use Common\Controller\App\SignController;
use Common\Model\CaptchaModel;
use Common\Model\HousingSkuModel;
use Common\Model\OccupationModel;
use Common\Model\PeripheryModel;
use Common\Model\RegionModel;
use Common\Model\RentalModel;
use Common\Model\RoomConfigureModel;
use Common\Model\RoommateModel;
use Common\Model\TrafficModel;
use Think\Upload\Driver\Auth;

class IndexController extends SignController
{
    public function is_login()
    {
        $member_id = session('member_id');
        if ($member_id) {
            $model = new MemberModel();
            $is_status = $model->where("id=$member_id")->getField('is_status');
            if ($is_status == 1) {
                $this->ajaxReturn(['code' => 200, 'msg' => '登录成功', 'shop_id' => $member_id]);
            } else {
                $this->ajaxReturn(['code' => 200, 'msg' => '新用户', 'shop_id' => $member_id]);
            }
        }
        $this->ajaxReturn(['code' => 300, 'msg' => '登录失败']);
    }

    /**
     * 获取职业.
     */
    public function getoccupation()
    {
        $model = new OccupationModel();
        $list = $model->field('id,name')->select();
        $this->ajaxReturn(['code' => 200, 'list' => $list]);
    }

    public function wxcode()
    {
        $member_id = session('member_id');
        $this->ajaxReturn(['code' => 200, 'shop_id' => $member_id, 'token' => authcode($member_id, 'ENCODE')]);
    }

    /**
     * 微信公众号进入平台登录.
     */
    public function wxlogin()
    {
        $member_id = session('member_id');
        $url = session('localhost_url');
        if ($url) {
            session('localhost_url', null);
            header("location:$url");
        }
        $url = C('URL')."/weixin/index.html?shop_id=$member_id&t=".time();
        header("location:$url");
    }

    public function flush()
    {
        $this->ajaxReturn(['code' => 200, 'msg' => '刷新成功']);
    }

    /**
     * 首页默认接口.
     */
    public function index()
    {
        $lng = I('param.lng') ? I('param.lng') : '104.059567';
        $lat = I('param.lat') ? I('param.lat') : '30.632553';
        $city = I('param.city') ? I('param.city') : '成都市';
        $regionlist = $this->getRegion($city);  //地区
        $rentallist = $this->getRental();      //出租类型
        $checklist = $this->getCheck();         //入住时间
        $configlist = $this->getConfig();       //配置
        $roommatelist = $this->getRoommate();   //室友
        $tarafficlist = $this->getTraffic();    //交通
        $peripherylist = $this->getPeriphery();    //周边
        $bannerlist = $this->getBanner();    //banner
        //获取房源列表
        $page = I('param.page') ? I('param.page') : 1;
        $limit = I('param.limit') ? I('param.limit') : 20;
        $num = ($page - 1) * $limit;
        $model = new HousingModel();
        $list = $model->alias('a')->join('left join neighbourhoods as b on a.neighbourhood=b.id')->where('a.nums>0')->field("b.name as neighbourhood_name,b.area,a.id,a.nums,a.size,a.population,a.configuration,a.pic,a.money")->order('a.sort desc,a.create_time desc')->limit($num, $limit)->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $regionmodel = new RegionModel();
                $region_name = $regionmodel->where("id={$v['area']}")->getField('name');
                $list[$k]['region_name'] = $region_name;
                $skumodel = new HousingSkuModel();
                $year_pay = $skumodel->where("pid={$v['id']}")->field('year_pay')->order('year_pay asc')->find();
                //$list[$k]['money'] = $year_pay['year_pay'];
                $configuration = explode(',', $v['configuration']);
                $list[$k]['configuration'] = $configuration;
            }
        } else {
            $list = [];
        }

        $this->ajaxReturn(['code' => 200, 'list' => $list, 'regionlist' => $regionlist, 'rentallist' => $rentallist, 'checklist' => $checklist, 'configlist' => $configlist, 'roommatelist' => $roommatelist, 'tarafficlist' => $tarafficlist, 'peripherylist' => $peripherylist, 'bannerlist' => $bannerlist]);
    }

    public function search()
    {
        $city = I('param.city'); //市
        $arae = I('param.area');  //县
        $street = I('param.street'); //街道
        $min_money = I('param.min_money');
        $max_money = I('param.max_money');
        $time = I('param.time');  //入住时间
        $peizhi = I('param.peizhi'); //配置
        $shiyou = I('param.shiyou'); //室友
        $jiaotong = I('param.jiaotong'); //交通
        $zhoubian = I('param.zhoubian'); //周边
        $ztype = I('param.ztype'); //租房类型    合租  整租
        $keyword = I('param.keyword'); //就是关键词
        $where = 'a.nums>0';
        if ($city) {
            //$where .= " and b.city='$city'";
        }
        if ($arae) {
            $where .= " and b.area='$arae'";
        }
        if ($street) {
            $where .= " and b.area='$street'";
        }
        if ($min_money && $max_money) {
            $where .= " and a.money>'$min_money' and a.money<'$max_money'";
        } elseif ($min_money) {
            $where .= " and a.money>'$min_money' ";
        } elseif ($max_money) {
            $where .= " and a.money<'$max_money'";
        }
        if ($time) {
            $where .= " and a.check='$time'";
        }
        if ($peizhi) {
            $where .= " and a.matching like '%$peizhi%'";
        }
        if ($shiyou) {
            $where .= " and a.roommate ='$shiyou'";
        }
        if ($jiaotong) {
            $where .= " and a.traffic like '%$jiaotong%'";
        }

        if ($zhoubian) {
            $where .= " and a.periphery like '%$zhoubian%'";
        }
        if ($ztype) {
            $where .= " and a.rental='$ztype'";
        }

        if(!empty($keyword)){
            $where .= " and b.name like '%$keyword%'";
        }
        //获取房源列表
        $page = I('param.page') ? I('param.page') : 1;
        $limit = I('param.limit') ? I('param.limit') : 20;
        $num = ($page - 1) * $limit;
        $model = new HousingModel();
        $list = $model->alias('a')->join('left join neighbourhoods as b on a.neighbourhood=b.id')->where($where)->field('b.name as neighbourhood_name,b.area,a.id,a.nums,a.size,a.population,a.configuration,a.pic,a.money')->order('a.sort desc,a.create_time desc')->limit($num, $limit)->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $regionmodel = new RegionModel();
                $region_name = $regionmodel->where("id={$v['area']}")->getField('name');
                $list[$k]['region_name'] = $region_name;
                $skumodel = new HousingSkuModel();
                $year_pay = $skumodel->where("pid={$v['id']}")->field('year_pay')->order('year_pay asc')->find();
                //$list[$k]['money'] = $year_pay['year_pay'];
                $configuration = explode(',', $v['configuration']);
                $list[$k]['configuration'] = $configuration;
            }
        } else {
            $list = [];
        }

        $this->ajaxReturn(['code' => 200, 'list' => $list]);
    }

    /**
     * 房屋详情.
     */
    public function housing_view()
    {
        $id = I('param.id');
        if (empty($id) || !is_numeric($id)) {
            $this->ajaxReturn(['code' => 300, 'msg' => '编号错误']);
        }
        $model = new HousingModel();
        $skumodel = new HousingSkuModel();
        $adminmodel = new AdminModel();
        $info = $model->where("id=$id")->field('id,nums,size,population,configuration,w_pic,cf_pic,g_pic,housekeeper_id,metro,transit,room_number,periphery,neighbourhood,title,money')->find();
        if (empty($info)) {
            $this->ajaxReturn(['code' => 300, 'msg' => '此房源数据不存在']);
        }
        $model = new MemberCollectionModel();
        $collertion_res = $model->where("housing_id={$info['id']}")->find();
        if ($collertion_res) {
            $info['is_collertion'] = 1;
        } else {
            $info['is_collertion'] = 0;
        }
        $nmodel = new NeighbourhoodsModel(); //获取小区
        $neighbourhoodsinfo = $nmodel->where("id={$info['neighbourhood']}")->find();
        $regionmodel = new RegionModel();
        $region_name = $regionmodel->where("id={$neighbourhoodsinfo['area']}")->getField('name');
        $info['region_name'] = $region_name;
        $regionmodel = new RegionModel();
        $province = $regionmodel->where("id={$neighbourhoodsinfo['province']}")->getField('name');
        $city = $regionmodel->where("id={$neighbourhoodsinfo['city']}")->getField('name');
        $area = $regionmodel->where("id={$neighbourhoodsinfo['area']}")->getField('name');
        $addr = $province.$city.$area.$neighbourhoodsinfo['addr'];
        $info['neighbourhoods_addr'] = $addr;
        $info['lng'] = $neighbourhoodsinfo['lng'];
        $info['lat'] = $neighbourhoodsinfo['lat'];
        $periphery = json_decode($info['periphery'], true);
        $pmodel = new PeripheryModel();
        $info['periphery'] = [];
        foreach ($periphery as $v) {
            $info['periphery'][] = $pmodel->where("id=$v")->getField('name');
        }
       // $year_pay = $skumodel->where("pid={$info['id']}")->field('year_pay')->order("year_pay asc")->find();
       // $info['money'] = $year_pay['year_pay'];
        $list = $skumodel->where("pid=$id")->select();  //获取sku
        //$arr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N'];
        $arr = ['H', 'O', 'N', 'E', 'Y', 'P'];

        $rcmodel = new RoomConfigureModel();
        foreach ($list as $k => $v) {
            $info['pic'][] = ['pic' => json_decode($v['pic'], true), 'name' => $arr[$k], 'skuid' => $v['id']];
            $list[$k]['pic'] = json_decode($v['pic'], true);
            $room_configure = json_decode($v['room_configure'], true);
            $list[$k]['room_configure'] = [];
            $list[$k]['name'] = $arr[$k];
            foreach ($room_configure as $v) {
                $list[$k]['room_configure'][] = $rcmodel->where("id=$v")->getField('name');
            }
        }
        $info['pic'][] = ['pic' => json_decode($info['g_pic'], true), 'name' => '公共区域', 'id' => $id];
        $info['pic'][] = ['pic' => json_decode($info['cf_pic'], true), 'name' => '厨房', 'id' => $id];
        $info['pic'][] = ['pic' => json_decode($info['w_pic'], true), 'name' => '卫生间', 'id' => $id];
        unset($info['w_pic']);
        unset($info['cf_pic']);
        unset($info['g_pic']);
        $info['configuration'] = explode(',', $info['configuration']);
        $admininfo = $adminmodel->where("id={$info['housekeeper_id']}")->field('username,intro,logo,mobile')->find();
        $info['housekeeper_username'] = $admininfo['username'];
        $info['housekeeper_intro'] = $admininfo['intro'];
        $info['housekeeper_logo'] = $admininfo['logo'];
        $info['mobile'] = $admininfo['mobile'];
        $hmodel = new HousekeeperCommentModel();
        $star = $hmodel->where("housekeeper_id={$info['housekeeper_id']}")->order('create_time desc')->getField('star');
        $info['housekeeper_star'] = $star ? $star : 5;
        $model = new NeighbourhoodsModel();
        $info['neighbourhoods_name'] = $model->where("id={$info['neighbourhood']}")->getField('name');
        $info['list'] = $list;
        $this->ajaxReturn(['code' => 200, 'info' => $info]);
    }

    /**
     * 分享赚钱.
     */
    public function getshare()
    {
        $member_id = session('member_id');
        $model = new MemberProfitModel();
        $total_money = $model->where("member_id=$member_id")->sun('money');
        $this->ajaxReturn(['code' => 200, 'total_money' => $total_money ? $total_money : 0]);
    }

    /**
     * 地图找房
     */
    public function getneighbourhood()
    {
        $model = new HousingModel();
        $list = $model->alias('a')->join('left join neighbourhoods as b on b.id=a.neighbourhood')->field('b.lat,b.lng,b.name,b.id,a.id as housing_id')->select();
        $this->ajaxReturn(['code' => 200, 'list' => $list]);
    }
    /**
     * 获取banner.
     */
    public function getBanner()
    {
        $model = new BannerModel();
        $list = $model->field('id,pic')->select();

        return $list;
    }

    /**
     * 获取周边.
     */
    public function getPeriphery()
    {
        $model = new PeripheryModel();
        $list = $model->field('id,name')->select();

        return $list;
    }

    /**
     * 获取交通.
     */
    public function getTraffic()
    {
        $model = new TrafficModel();
        $list = $model->field('id,name')->select();

        return $list;
    }

    /**
     * 获取室友.
     */
    public function getRoommate()
    {
        $model = new RoommateModel();
        $list = $model->field('id,name')->select();

        return $list;
    }

    /**
     * 获取配置.
     */
    public function getConfig()
    {
        $model = new ConfigureModel();
        $list = $model->field('id,name')->select();

        return $list;
    }

    /**
     * 获取入住时间.
     */
    public function getCheck()
    {
        $model = new CheckModel();
        $list = $model->field('id,name')->select();

        return $list;
    }

    /**
     * 获取出租类型.
     */
    public function getRental()
    {
        $model = new RentalModel();
        $list = $model->field('id,name')->select();

        return $list;
    }

    /**
     * 获取下级区域
     */
    public function getRegList()
    {
        $region_id = I('param.region_id');
        if (empty($region_id) || !is_numeric($region_id)) {
            $this->ajaxReturn(['code' => 300, 'msg' => '参数错误']);
        }
        $model = new RegionModel();
        $list = $model->where("pid=$region_id")->field('id,name')->select();
        $this->ajaxReturn(['code' => 200, 'list' => $list]);
    }
    /**
     * 获取区域
     */
    public function getRegion($data)
    {
        if (empty($data)) {
            $this->ajaxReturn(['code' => 200, 'msg' => '参数错误']);
        }
        $model = new RegionModel();
        $region_id = $model->where("name like '%$data%'")->getField('id');
        if (empty($region_id)) {
            $this->ajaxReturn(['code' => 300, 'msg' => '此区域不存在']);
        }
        $list = $model->where("pid=$region_id  and is_show=1")->field('id,name')->select();

        return $list;
    }
    /**
     * 获取短信验证码
     */
    public function send()
    {
        $mobile = I('param.mobile');
        if (empty($mobile)) {
            $this->ajaxReturn(['code' => 300, 'msg' => '此手机号错误']);
        }
        $code = rand(1000, 9999);
        $model = new CaptchaModel();
        $captchainfo = $model->where("unique_str='$mobile' and is_used=0")->field('invalid_time')->order('create_time desc')->find();
        if (time() < strtotime($captchainfo['invalid_time'])) {
            $this->ajaxReturn(['code' => 300, 'msg' => '你已发送验证码，还未使用请去手机短信里查看']);
        }
        $cap = $model->where("unique_str='$mobile'")->field('invalid_time,create_time')->order('create_time desc')->find();
        if (time() - strtotime($cap['create_time']) < 60) {
            $this->ajaxReturn(['code' => 300, 'msg' => '你发送短信过于频繁，请稍后再试']);
        }
        $datas['unique_str'] = $mobile;
        $datas['captcha'] = $code;
        $datas['invalid_time'] = date('Y-m-d H:i:s', time() + 300);
        $datas['type'] = 'normal';
        $datas['create_time'] = date('Y-m-d H:i:s', time());
        $res = $model->add($datas);
        if (empty($res)) {
            $this->ajaxReturn(['code' => 300, 'msg' => '手机验证码发送失败，请稍后再试！']);
        }

        header('Content-type: text/html; charset=utf-8');
        $post_data = array();
        $post_data['userid'] = 1197;
        $post_data['account'] = 'fcxjjkde';
        $post_data['password'] = 'dc2016yhedfr';
        $post_data['mobile'] = $mobile;
        $post_data['sendtime'] = '';

        $content = "【蜂巢小家】您好你的验证码为$code,请小心保管。";
        $post_data['content'] = $content;
        $url = 'http://dc.28inter.com/sms.aspx?action=send';

        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        $this->echo_xmlarr($data);
    }

    // 页面显示数组格式，用于调试
    public function echo_xmlarr($res)
    {
        $res = $this->xml_to_array($res);
        if ($res['returnsms']['returnstatus'] == 'Success') {
            $this->ajaxReturn(['code' => '200', 'msg' => '手机验证码发送成功']);
        } else {
            $this->ajaxReturn(['code' => '200', 'msg' => '手机验证码发送失败']);
        }
    }
    // XML格式转数组格式
    public function xml_to_array($xml)
    {
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if (preg_match_all($reg, $xml, $matches)) {
            $count = count($matches[0]);
            for ($i = 0; $i < $count; ++$i) {
                $subxml = $matches[2][$i];
                $key = $matches[1][$i];
                if (preg_match($reg, $subxml)) {
                    $arr[$key] = $this->xml_to_array($subxml);
                } else {
                    $arr[$key] = $subxml;
                }
            }
        }

        return $arr;
    }

    /**
     * 获取七牛唯一标示（图片）.
     */
    public function get_qiniu()
    {
        $Qiniu = new Auth('aBruJjiPVgqa4vVo1HwwH7dQ1mFei57U4Qfz2m7V', '_L5LO2Emj9tkaVUfN59DVkdfd5zQTu4WXI0374xg');
        $token = $Qiniu->uploadToken('line-img');
        $this->ajaxReturn(['code' => 200, 'token' => $token, 'bucket' => 'line-img']);
    }
}
